package cn.xiongxf.service.impl;

import cn.xiongxf.constant.RedisKeyConstant;
import cn.xiongxf.domain.User;
import cn.xiongxf.domain.UserBaseInfo;
import cn.xiongxf.domain.UserGrowLog;
import cn.xiongxf.domain.UserRecommendCode;
import cn.xiongxf.exception.GlobalCustomException;
import cn.xiongxf.mapper.UserBaseInfoMapper;
import cn.xiongxf.service.IUserBaseInfoService;
import cn.xiongxf.service.IUserGrowLogService;
import cn.xiongxf.service.IUserRecommendCodeService;
import cn.xiongxf.service.IUserService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 会员基本信息 服务实现类
 * </p>
 *
 * @author xiongxiaofu
 * @since 2022-08-12
 */
@Service
public class UserBaseInfoServiceImpl extends ServiceImpl<UserBaseInfoMapper, UserBaseInfo> implements IUserBaseInfoService {
    @Autowired
    private IUserRecommendCodeService userRecommendCodeService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private IUserGrowLogService userGrowLogService;

    /**
     * 保荐用户基本信息
     * @param id 用户ID
     * @param regChannel 注册渠道
     * @param recommendCode 推荐码
     */
    @Override
    public void save(Long id, Integer regChannel, String recommendCode) {
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setId(id);
        userBaseInfo.setCreateTime(System.currentTimeMillis());
        userBaseInfo.setRegChannel(regChannel);
        userBaseInfo.setLevel(0);

        // 设置推荐人ID
        saveReferId(userBaseInfo, recommendCode);

        // 保荐用户基本信息
        insert(userBaseInfo);
    }

    // 抽取方法：设置推荐人ID
    private void saveReferId(UserBaseInfo userBaseInfo, String recommendCode) {
        if (StringUtils.hasLength(recommendCode)){
            // 若推荐码不为空，从DB中查询推荐人ID
            UserRecommendCode userRecommendCode = userRecommendCodeService
                    .selectOne(new EntityWrapper<UserRecommendCode>().eq("recommend_code", recommendCode));
            if (userRecommendCode != null){
                Long referId = userRecommendCode.getUserId();
                // 根据推荐人ID从Redis中查询推荐码
                Object recommendCodeObj = redisTemplate.opsForValue().get(RedisKeyConstant.RECOMMEND_CODE_KEY + referId);
                if (recommendCodeObj != null){
                    // 若Redis中有推荐码：
                    // 保存注册用户的推荐人ID
                    userBaseInfo.setReferId(referId);
                    // 保存用户（推荐人）成长日志：赠送推荐人100成长值
                    saveUserGrowLog(referId);

                    // 删除Redis中保存的推荐码（一个推荐码只能注册一次）
                    redisTemplate.delete(RedisKeyConstant.RECOMMEND_CODE_KEY + referId);
                }else {
                    throw new GlobalCustomException("邀请码已被使用！请输入其它邀请码或不使用邀请码直接注册");
                }
            }else {
                throw new GlobalCustomException("邀请码不存在！请检查邀请码或不使用邀请码直接注册");
            }
        }
    }

    // 抽取方法：保存用户（推荐人）成长日志：赠送推荐人100成长值
    private void saveUserGrowLog(Long referId) {
        UserGrowLog userGrowLog = new UserGrowLog();
        userGrowLog.setCreateTime(System.currentTimeMillis());
        userGrowLog.setUserId(referId);
        userGrowLog.setFromReason("推荐码注册成功赠送");
        userGrowLog.setScore(100);
        userGrowLogService.insert(userGrowLog);
    }
}
